import { ref, reactive } from 'vue'
import API_CONFIG from '../config/api.js'
import { queuedFetch } from '../utils/queuedRequest.js'

export function useIndicatorAPI() {
  const isLoading = ref(false)
  const loadingProgress = ref(0)
  const error = ref(null)

  // 获取单个指标数据 - 使用队列化请求
  const getIndicatorData = async (indicatorName) => {
    return new Promise((resolve, reject) => {
      try {
        const name = typeof indicatorName === 'object' ? indicatorName.name : indicatorName
        const extraWhere = typeof indicatorName === 'object' && indicatorName.where ? ` and ${indicatorName.where}` : ''
        console.debug('[IndicatorAPI] 开始获取指标数据:', name, extraWhere ? `(附加条件: ${extraWhere})` : '')
        
        // 准备POST数据 - 使用配置文件中的设置
        var postData = new URLSearchParams()
        const dbConfig = API_CONFIG.getDatabaseConfig()
        const requestParams = dbConfig.API.REQUEST_PARAMS
        
        postData.append('action', requestParams.action)
        postData.append('jdbcName', requestParams.jdbcName)
        postData.append('enc', requestParams.enc)
        
        // SQL查询 - 使用配置文件中的SQL模板
        let sql = API_CONFIG.buildSQL.getIndicatorData(name, null, extraWhere)
        sql = encodeURIComponent(sql)
        sql = btoa(sql)
        
        postData.append('sql', sql)
        postData.append('pageIndex', 'undefined')
        postData.append('pageSize', requestParams.pageSize)
        postData.append('isSys', requestParams.isSys)
        postData.append('t', Date.now().toString())
        
        // 完全按照原始代码构建URL
        const apiUrl = `http://${window.location.host}/coolv/edatasource/jdbcmgr.do`
        
        // 设置请求头 - 使用配置文件中的设置
        const headers = API_CONFIG.HEADERS
        
        // 使用队列化的 fetch 请求
        queuedFetch(apiUrl, {
          method: 'POST',
          headers: {
            'Content-Type': headers['Content-Type'],
            'X-Requested-With': headers['X-Requested-With'],
            'Accept': headers['Accept'],
            'Accept-Language': headers['Accept-Language']
          },
          body: postData.toString()
        }, {
          name: `指标: ${name}`,
          priority: 10  // 指标数据最高优先级
        })
        .then(response => {
          if (!response.ok) {
            throw new Error(`请求失败: ${response.status}`)
          }
          return response.json()
        })
        .then(jsonResponse => {
          console.debug('[IndicatorAPI] 请求成功:', name, 'records:', Array.isArray(jsonResponse?.datas) ? jsonResponse.datas.length : 0)
          resolve(jsonResponse)
        })
        .catch(e => {
          console.error('[IndicatorAPI] 请求失败:', name, e)
          reject(e)
        })
        
      } catch (e) {
        console.error('[IndicatorAPI] 获取数据异常:', e)
        reject(e)
      }
    })
  }

  // 获取净利润数据（特殊指标，需要转换单位为亿元）
  const getNetProfitData = async () => {
    try {
      console.debug('[IndicatorAPI] 开始获取净利润数据...')
      
      // 准备POST数据
      var postData = new URLSearchParams()
      const dbConfig = API_CONFIG.getDatabaseConfig()
      const requestParams = dbConfig.API.REQUEST_PARAMS
      
      postData.append('action', requestParams.action)
      postData.append('jdbcName', requestParams.jdbcName)
      postData.append('enc', requestParams.enc)
      
      // 查询净利润
      let sql = `select buss_dt, index_value from audit_index_total where index_nm='五、净利润（亏损以"-"号填列）' and org_no='00000' order by buss_dt desc`
      sql = encodeURIComponent(sql)
      sql = btoa(sql)
      
      postData.append('sql', sql)
      postData.append('pageIndex', 'undefined')
      postData.append('pageSize', requestParams.pageSize)
      postData.append('isSys', requestParams.isSys)
      postData.append('t', Date.now().toString())
      
      const apiUrl = `http://${window.location.host}/coolv/edatasource/jdbcmgr.do`
      const headers = API_CONFIG.HEADERS
      
      const profitResponse = await queuedFetch(apiUrl, {
        method: 'POST',
        headers: {
          'Content-Type': headers['Content-Type'],
          'X-Requested-With': headers['X-Requested-With'],
          'Accept': headers['Accept'],
          'Accept-Language': headers['Accept-Language']
        },
        body: postData.toString()
      }, {
        name: '净利润',
        priority: 10
      })
      
      const profitData = await profitResponse.json()
      
      // 转换单位为亿元
      if (profitData.datas && profitData.datas.length > 0) {
        const convertedData = profitData.datas.map(row => {
          const date = row[0]
          const profit = parseFloat(row[1]) || 0
          // 转换为亿元：元 / 100000000
          const profitInYi = profit / 100000000
          return [date, '', '00000', profitInYi, '']
        })
        
        console.debug('[IndicatorAPI] 净利润数据获取完成，共', convertedData.length, '条数据')
        
        return {
          datas: convertedData
        }
      }
      
      console.warn('[IndicatorAPI] 净利润数据获取失败：数据不足')
      return { datas: [] }
      
    } catch (err) {
      console.error('[IndicatorAPI] 获取净利润数据失败:', err)
      throw err
    }
  }

  // 批量加载关键指标
  const loadKeyIndicators = async (indicators) => {
    isLoading.value = true
    error.value = null

    try {
      // 使用 Promise.allSettled 替代 Promise.all，避免一个失败导致全部失败
      // 注意：不在这里计算进度，完全依赖全局队列的进度显示
      const promises = indicators.map(async (indicator) => {
        try {
          const indicatorName = typeof indicator === 'object' ? indicator.name : indicator
          
          // 特殊处理：净利润需要单位转换
          if (indicatorName === '净利润') {
            const data = await getNetProfitData()
            return { indicator, data, success: true }
          }
          
          const data = await getIndicatorData(indicator)
          return { indicator, data, success: true }
        } catch (err) {
          const indicatorName = typeof indicator === 'object' ? indicator.name : indicator
          console.error(`指标 ${indicatorName} 加载失败:`, err)
          return { indicator, error: err, success: false }
        }
      })

      const results = await Promise.allSettled(promises)
      // 提取实际结果
      return results.map(result => result.status === 'fulfilled' ? result.value : result.reason)
    } catch (err) {
      error.value = err
      throw err
    } finally {
      isLoading.value = false
    }
  }

  return {
    isLoading,
    loadingProgress,
    error,
    getIndicatorData,
    loadKeyIndicators
  }
}

